import { View, Text } from "@tarojs/components";
import { useState, useEffect } from "react";
import Taro from "@tarojs/taro";

import "./index.less";

// 需要预加载的图片列表
const IMAGE_LIST = [
  // 主背景图
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDbX9o8En3Uwqh3v5Ai1IPUFF0Cfm1kAACFxkAAqpXgVeq77mlXIE13TYE.png",
  
  // 宝石盘背景图
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDe0Ro8fG8NY0HpDQbsS5a8YJlAXj7MgACTCEAAgm3kVdokKKQ4eTIzTYE.jpg",
  
  // 各种宝石图片
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDe0Jo8fG86LQ55wEn4XqdXKOi1zCPHwACSiEAAgm3kVfAdFazE3qw3DYE.png", // 红色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDe0Bo8fG371QHiXEzAaSMYUO0oEXWVgACSCEAAgm3kVd0dE_vl27q4jYE.png", // 蓝色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDez9o8fG3DnUzAT-nJVd9EDxcCfxRgAACRyEAAgm3kVcTMz2farlPLTYE.png", // 绿色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDe0Fo8fG37wMFEY0CzuRye0ZQ8RRN8AACSSEAAgm3kVcipeSVCe3TjjYE.png", // 粉色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDez1o8fG3gnh1di8o4dh3i1QIVhp2xAACRSEAAgm3kVeXx91YLBbu4jYE.png", // 黑色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDez5o8fG3IsmpaBMkWKVe-PE5C070kQACRiEAAgm3kVfuZEJhbpkwhTYE.png", // 白色宝石
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDe0No8fG8lC520Z4sqxuv2szLiU51hwACSyEAAgm3kVe9agb3mknfwDYE.png", // 金色宝石
  
  // 面板背景图
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDfWho8gHeLmlviqqjLQ7kZvtJxaM_ywACRyQAAgm3kVe1hknA9Jvl6TYE.png",
  
  // 图标
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDfc9o8gVE-2viMA7fMvMU2dzy6ETH5AACzyQAAgm3kVcr6w5dXb8_HDYE.png", // 皇冠图标
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDfedo8ggG-4V1CcNxJr5zvgFTaCJ0dwAC7CQAAgm3kVfEy4-9Po_yzDYE.png", // 特权图标
  
  // 卡片背景图
  "https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEDg_Fo8146L0P8roMDfBTGKgcXQ0CloQACjB0AAgm3mVed2k2bhu728jYE.jpg"
];

export default function Loading() {
  const [progress, setProgress] = useState<number>(0);
  const [status, setStatus] = useState<string>('正在加载资源...');

  // 预加载图片
  const preloadImages = () => {
    let loadedCount = 0;
    const totalImages = IMAGE_LIST.length;
    
    // 更新进度的函数
    const updateProgress = () => {
      loadedCount++;
      const newProgress = Math.round((loadedCount / totalImages) * 100);
      setProgress(newProgress);
      
      // 更新状态文本
      if (newProgress < 30) {
        setStatus('正在加载游戏资源...');
      } else if (newProgress < 60) {
        setStatus('正在初始化游戏界面...');
      } else if (newProgress < 90) {
        setStatus('正在加载游戏数据...');
      } else {
        setStatus('即将进入游戏...');
      }
      
      // 所有图片加载完成后，500ms后跳转
      if (loadedCount === totalImages) {
        setTimeout(() => {
          redirectToMain();
        }, 500);
      }
    };
    
    // 使用Taro预加载所有图片
    IMAGE_LIST.forEach((src) => {
      Taro.getImageInfo({
        src: src
      }).then(() => {
        updateProgress();
      }).catch(() => {
        // 即使加载失败也继续
        updateProgress();
      });
    });
  };

  // 跳转到主页面
  const redirectToMain = () => {
    const router = Taro.getCurrentInstance().router;
    const roomIdParam = router?.params?.roomId;
    const playerIpParam = router?.params?.playerIp;
    
    let url = '/pages/main/index';
    if (roomIdParam) {
      url += `?roomId=${roomIdParam}`;
      if (playerIpParam) {
        url += `&playerIp=${playerIpParam}`;
      }
    }
    
    Taro.redirectTo({ url });
  };

  // 页面加载时开始加载进度
  useEffect(() => {
    // 开始预加载图片
    preloadImages();
    
    // 设置5秒超时，防止图片加载失败导致无法跳转
    const timeout = setTimeout(() => {
      redirectToMain();
    }, 5000);
    
    return () => {
      clearTimeout(timeout);
    };
  }, []);

  return (
    <View className='loading-container'>
      <View className='loading-logo'></View>
      <Text className='loading-title'>MBTI宝石游戏</Text>
      <Text className='loading-subtitle'>正在为您准备精彩的游戏体验</Text>
      
      <View className='progress-container'>
        <View className='progress-bar'>
          <View 
            className='progress-fill' 
            style={{ width: `${progress}%` }}
          />
        </View>
        <Text className='progress-text'>{progress}%</Text>
      </View>
      
      <Text className='loading-status'>{status}</Text>
      
      <View className='loading-dots'>
        <span></span>
        <span></span>
        <span></span>
      </View>
    </View>
  );
}